package com.niit.service;

import com.niit.mapper.MachineMapper;
import com.niit.pojo.Machine;
import com.niit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MachineService {

    public List<Machine> findMachines() {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            return mapper.findMachines();
        }
    }

    public Machine findMachineById(int id) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            return mapper.findMachineById(id);
        }
    }

    public int addMachine(Machine machine) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            int result = mapper.addMachine(machine);
            sqlSession.commit();
            return result;
        } catch (Exception e) {
            System.err.println("添加机器失败: " + e.getMessage());
            throw e; // 抛出异常，让调用者处理
        }
    }



    public int updateMachine(Machine machine) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            int result = mapper.updateMachine(machine);
            sqlSession.commit();
            return result;
        } catch (Exception e) {
            System.err.println("更新机器失败: " + e.getMessage());
            throw e; // 抛出异常，让调用者处理
        }
    }

    public int deleteMachine(int id) {
        System.out.println("开始删除机器，ID: " + id);
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            int result = mapper.deleteMachine(id);
            System.out.println("删除结果: " + result);
            sqlSession.commit();
            return result;
        } catch (Exception e) {
            System.err.println("删除机器失败: " + e.getMessage());
            e.printStackTrace(); // 打印完整堆栈信息
            throw e;
        }
    }

    // 添加搜索方法
    public List<Machine> searchMachines(String keyword) {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            MachineMapper mapper = sqlSession.getMapper(MachineMapper.class);
            Map<String, Object> params = new HashMap<>();
            params.put("keyword", "%" + keyword + "%");
            return mapper.searchMachines(params);
        }
    }
}